﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using HSHLogicLayer;
using HSHLogicLayer.DataWS;
using System.Net.Mail;
using System.IO;
using System.Text.RegularExpressions;

namespace TaskVision
{
    public partial class EventRakazim2 : Form
    {

        #region PrivateMembers

        DSRakazim ds = new DSRakazim();
        int m_EventID;
        string m_EventName;
        bool expanded = false;

        #endregion

        #region Loading

        public EventRakazim2(int EventID, string EventName)
        {
            InitializeComponent();
            m_EventID = EventID;
            m_EventName = EventName;
            //we have to redo all the wrk here because VS don't let us bind with an outgoing value (the event ID)
            loaddata(m_EventID);
            collapse();

        }

        private void EventRakazim2_Shown(object sender, EventArgs e)
        {
            ColorDG();
            //select unsent,changed
            progressBar1.Maximum = 100;
        }

        #endregion

        #region UIMethods

        #region collaps/expand

        private void collapse()
        {
            splitContainer3.Panel2Collapsed = true;
            splitContainer3.Panel1Collapsed = false;
            expanded = false;
            btnExpand.Text = @"הצג פרטים";

        }

        private void btnExpand_Click(object sender, EventArgs e)
        {
            if (!expanded)
            {
                splitContainer3.Panel1Collapsed = false;
                splitContainer3.Panel2Collapsed = false;
                expanded = true;
                btnExpand.Text = @"הסתר פרטים";
            }
            else
            {
                collapse();
            }

        }

        #endregion

        #region buttons

        private void btnSend_Click(object sender, EventArgs e)
        {

            DSRakazim.GetRakazimToEventRow m_row = (DSRakazim.GetRakazimToEventRow)((DataRowView)getRakazimToEventDataGridView.SelectedRows[0].DataBoundItem).Row;
            bool notsent = string.IsNullOrEmpty(m_row["SentDate"].ToString());
            if (notsent)
            {
                //send(getRakazimToEventDataGridView.SelectedRows[0]);
                loaddata(m_EventID);
                ColorDG();
            }
            else
            {
                if (HebMessageBox.Show("טופס זה כבר נשלח לרכז, אם תשלח אותו שוב, כל הנתונים יימחקו ויישלח טופס חדש, האם להמשיך?", "שגיאה בשליחת הטופס", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    send(getRakazimToEventDataGridView.SelectedRows[0]);
                    loaddata(m_EventID);
                    ColorDG();
                }
                else
                {
                    HebMessageBox.Show("הטופס לא נשלח ל:" + (string)m_row["FirstName"] + " " + (string)m_row["LastName"]);
                }
            }
        }

        private void sndall_Click(object sender, EventArgs e)
        {
            foreach (int i in CheckedRowsArray())
            {
                if (!(string.IsNullOrEmpty(getRakazimToEventDataGridView.Rows[i].Cells["IsApproved"].Value.ToString())))
                {
                    if ((bool)getRakazimToEventDataGridView.Rows[i].Cells["IsApproved"].Value != false)
                    {
                        if (HebMessageBox.Show("הטופס שנשלח לרכז ביישוב " + getRakazimToEventDataGridView.Rows[i].Cells["jurisdiction"].Value.ToString().Trim() + @" כבר אושר, האם לשלוח מחדש (פעולה זאת תבטל את האישור הקיים)", "שליחת טופס שאושר", MessageBoxButtons.YesNo, MessageBoxIcon.Stop) == DialogResult.No)
                        {
                            getRakazimToEventDataGridView.Rows[i].Cells["Checked"].Value = false;
                        }
                    }
                }
            }
            int rownum = CountCheckedRows();
            int rowindex=1;
            if (rownum > 0)
            {
                this.Cursor = Cursors.WaitCursor;
                DataGridViewRowCollection RowCollection = getRakazimToEventDataGridView.Rows;
                foreach (DataGridViewRow row in RowCollection)
                {

                    progressBar1.Maximum = 4;
                    progressBar1.Value = 0;
                    progressBar1.Step = 1;
                    progressBar1.Visible = true;
                    lblProgress.Visible = true;
                    lblProgress.Text = (rowindex-1) + " מתוך " + rownum;
                    Application.DoEvents();
                    if ((bool?)row.Cells["sending"].Value == true)
                    {
                        send(row);
                    }
                    ColorDG();
                    rowindex++;
                }
                progressBar1.Visible = false;
                lblProgress.Visible = false;
                this.Cursor = Cursors.Default;
                loaddata(m_EventID);
                ColorDG();
            }
            else
            {
                HebMessageBox.Show("יש לסמן לפחות רכז אחד");
            }
        }


        private void displayPDF_Click(object sender, EventArgs e)
        {
            string pdfpath = string.Empty;
            FolderBrowserDialog savefile = new FolderBrowserDialog();
            savefile.Description = "בחר היכן לשמור את הקובץ";
            if (savefile.ShowDialog() == DialogResult.OK)
            {
                string badEventName = m_EventName.ToString().Trim();
                string regex = String.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidFileNameChars())));
                Regex removeInvalidChars = new Regex(regex, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.CultureInvariant);
                string EventName = removeInvalidChars.Replace(badEventName, "");
                pdfpath = savefile.SelectedPath + @"\" + EventName+ @"\";
                if (Directory.Exists(pdfpath))
                {
                    for (int i = 1; ; i++)
                    {
                        if (Directory.Exists(pdfpath))
                        {
                            continue;
                        }
                        else
                        {
                            pdfpath.Remove(pdfpath.Length - 1, 1);
                            pdfpath = pdfpath + i + @"\";
                            break;
                        }
                    }
                }
                Directory.CreateDirectory(pdfpath);
                if (CountCheckedRows() > 0)
                {
                    foreach (DataGridViewRow row in getRakazimToEventDataGridView.Rows)
                    {
                        if ((bool?)row.Cells["sending"].Value == true)
                        {
                            getRakazimToEventDataGridView.ClearSelection();
                            row.Selected = true;
                            SavePDFtofile(pdfpath);
                        }
                    }
                    System.Diagnostics.Process.Start(pdfpath);
                    loaddata(m_EventID);
                    ColorDG();
                }
                else
                {
                    HebMessageBox.Show("יש לסמן לפחות רכז אחד");
                }
            }
        }

        private void btnSendReminder_Click(object sender, EventArgs e)
        {
            if (CountCheckedRows() > 0)
            {
                foreach (DataGridViewRow row in getRakazimToEventDataGridView.Rows)
                {
                    if ((bool?)row.Cells["sending"].Value == true)
                    {
                        getRakazimToEventDataGridView.ClearSelection();
                        row.Selected = true;
                        SendReminder();
                    }
                }
                loaddata(m_EventID);
                ColorDG();
            }
            else
                HebMessageBox.Show("יש לסמן לפחות רכז אחד");
        }

        private void btnResend_Click(object sender, EventArgs e)
        {

            if (CountCheckedRows() > 0)
            {
                foreach (DataGridViewRow row in getRakazimToEventDataGridView.Rows)
                {
                    if ((bool?)row.Cells["sending"].Value == true)
                    {
                        getRakazimToEventDataGridView.ClearSelection();
                        row.Selected = true;
                        send(row);
                    }
                }
                loaddata(m_EventID);
                ColorDG();
            }
            else
                HebMessageBox.Show("יש לסמן לפחות רכז אחד");
        }

        #endregion

        #region Menus

        private void getRakazimToEventDataGridView_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                Point p = new Point(e.X - (mnuRakazim.Width), e.Y);
                mnuRakazim.Show(getRakazimToEventDataGridView.PointToScreen(p));
            }
        }


        private void SelectAll_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow currrow in getRakazimToEventDataGridView.Rows)
            {
                currrow.Cells["sending"].Value = true;
            }
        }

        private void SelectUnsent_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow currrow in getRakazimToEventDataGridView.Rows)
            {
                currrow.Cells["sending"].Value = false;
                if (((string)currrow.Cells["status"].Tag) == "unsent")
                {
                    currrow.Cells["sending"].Value = true;
                }
            }
        }

        private void SelectUnAuthorised_Click(object sender, EventArgs e)
        {

            foreach (DataGridViewRow currrow in getRakazimToEventDataGridView.Rows)
            {
                currrow.Cells["sending"].Value = false;
                if (((string)currrow.Cells["status"].Tag) == "sent")
                {
                    currrow.Cells["sending"].Value = true;
                }
            }
        }

        private void ClearSelection_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow currrow in getRakazimToEventDataGridView.Rows)
            {
                currrow.Cells["sending"].Value = false;
            }
        }

        #endregion

        #endregion

        #region Helper Methods

        #region Datagrid

        private void loaddata(int EventID)
        {
            ds = (DSRakazim)DataLayerSingleton.Instance().RakazEvent(EventID).DataSet;
            getRakazimToEventBindingSource.DataSource = ds;
            getRakazPeopleInEventBindingSource.DataSource = getRakazimToEventBindingSource;
            getRakazPeopleInEventBindingSource.DataMember = "GetRakazimToEvent_GetRakazPeopleInEvent";
            getRakazimToEventBindingNavigator.BindingSource = getRakazimToEventBindingSource;


        }

        private void ColorDG()
        {
            getRakazimToEventDataGridView.ClearSelection();
            getRakazPeopleInEventDataGridView.ClearSelection();
            foreach (DataGridViewRow row in getRakazimToEventDataGridView.Rows)
            {
                getRakazimToEventDataGridView.ClearSelection();
                getRakazPeopleInEventDataGridView.ClearSelection();
                string status = "לא נשלח";
                if (!string.IsNullOrEmpty(row.Cells["SentDate"].Value.ToString()))
                {
                    status = "נשלח";
                    row.Cells["status"].Tag = "sent";
                    row.Cells["status"].Value = status;
                    row.Cells["status"].Style.BackColor = Color.Yellow;
                    row.Cells["status"].Style.ForeColor = Color.Black;
                    row.Cells["status"].Style.SelectionBackColor = Color.FromArgb(255, 255, 158);
                    row.Cells["status"].Style.SelectionForeColor = Color.Black;
                    //row.DefaultCellStyle.BackColor = Color.Orange;
                    //row.DefaultCellStyle.ForeColor = Color.White;
                    //row.DefaultCellStyle.SelectionBackColor = Color.DarkOrange;
                    if ((bool)row.Cells["IsApproved"].Value)
                    {
                        status = "אושר";
                        row.Cells["status"].Tag = "approved";
                        row.Cells["status"].Value =status;
                        row.Cells["status"].Style.BackColor = Color.LawnGreen;
                        row.Cells["status"].Style.ForeColor = Color.Black;
                        row.Cells["status"].Style.SelectionBackColor = Color.Green;
                        row.Cells["status"].Style.SelectionForeColor = Color.Black;
                    }
                }
                else
                {
                    row.Cells["status"].Tag = "unsent";
                    row.Cells["status"].Value = status;
                    row.Cells["status"].Style.BackColor = Color.White;
                    row.Cells["status"].Style.ForeColor = Color.Black;
                    row.Cells["status"].Style.SelectionBackColor = Color.Blue;
                    row.Cells["status"].Style.SelectionForeColor = Color.White;
                }
                string s = Convert.ToString((((DataRowView)row.DataBoundItem).Row)["TotalPrice"]);
                if (string.IsNullOrEmpty(s))
                {
                    //row.Cells["TotalPrice"].Value = CalTotPrice();
                }
                else
                {
                    if (isChanged(row))
                    {

                        status = "שונה";
                        row.Cells["status"].Tag = "error";
                        row.Cells["status"].Value = status;
                        row.Cells["status"].Style.BackColor = Color.Red;
                        row.Cells["status"].Style.ForeColor = Color.Black;
                        row.Cells["status"].Style.SelectionBackColor = Color.OrangeRed;
                        row.Cells["status"].Style.SelectionForeColor = Color.Black;
                    }
                }
            } 
        }

        private bool isChanged(DataGridViewRow DGVRow)
        {
            DateTime sentdate = (DateTime)(ds.GetRakazimToEvent.Rows[DGVRow.Index]["SentDate"]);
            foreach (DSRakazim.GetRakazPeopleInEventRow peprow in ds.GetRakazimToEvent.Rows[DGVRow.Index].GetChildRows(ds.Relations[0]))
            {
                DateTime update = peprow.StatusUpdateDate;
                if (sentdate < update)
                    return true;
            }

            return false;


        }

        private int CalTotPrice()
        {
            int tot = 0;
            foreach (DataGridViewRow row in getRakazPeopleInEventDataGridView.Rows)
            {
                tot = tot + (Convert.ToInt32(row.Cells["Payment"].Value));
            }
            return tot;
        }

        #endregion
        
        #region PDFHandling

        private bool send(DataGridViewRow DGVrow)
        {
            bool RetVal = false;
            string PDFPath= null ;
            DSRakazim pdfds = new DSRakazim();
            DSRakazim.GetRakazimToEventRow row = (DSRakazim.GetRakazimToEventRow)ds.GetRakazimToEvent.Rows[DGVrow.Index];
            pdfds.GetRakazimToEvent.ImportRow(row);
            foreach (DSRakazim.GetRakazPeopleInEventRow peprow in ds.GetRakazimToEvent.Rows[DGVrow.Index].GetChildRows(ds.Relations[0]))
            {
                pdfds.GetRakazPeopleInEvent.ImportRow(peprow);
            }
            progressBar1.PerformStep();
            //progressBar1.Value = 10;
            //lblProgress.Text = "יוצר PDF";
            Application.DoEvents();
            lblProgress.Visible = true;
            try
            {
                PDFPath = CreatePDF(pdfds);
                progressBar1.PerformStep();
                //progressBar1.Value = 30;
                //lblProgress.Text = "שומר במסד נתונים";
                Application.DoEvents();
                //System.Diagnostics.Process.Start(PDFPath);
                if (!(PDFPath == null))
                {
                    int RakazEventID;
                    RakazEventID = SendToDB(PDFPath, pdfds);
                    progressBar1.PerformStep();
                    //progressBar1.Value = 70;
                    //lblProgress.Text = "שולח לרכז";
                    Application.DoEvents();
                    if (RakazEventID != -1)
                    {
                        bool isSent;
                        isSent = SendToRakaz(PDFPath, pdfds, RakazEventID, false);
                        //progressBar1.Value = 100;
                        //Application.DoEvents();
                        if (isSent)
                            RetVal = true;
                    }
                }
                //if it WAS sent, we should update the DB again and add the time it was sent
                //remember to delete the file if it was sent to DB and to Rakaz
            }
            catch (Exception ex)
            {
                HebMessageBox.Show(ex.Message);
            }
            finally
            {
                //loaddata(m_EventID);
                //ColorDG();
                if (!string.IsNullOrEmpty(PDFPath))
                {
                    File.Delete(PDFPath);
                }
                
            }
            return RetVal;

        }

        private string CreatePDF(DSRakazim pdfds)
        {
            string retval = null;
            //Create the pdf and return the path where you put it
            PDFHelper Ph = new PDFHelper();
            try
            {
                retval= Ph.CreatePDF(pdfds,m_EventName);
            }
            catch (Exception ex)
            {
                HebMessageBox.Show(ex.Message);
            }
            return retval;
        }

        private int SendToDB(String path, DSRakazim details)
        {
            int retval = -1;
            //Convert the PDF file into byte array
            PDFHelper Ph= new PDFHelper();
            Byte[] PDFB = Ph.blobPDF(path);
            string Comments = "";
            //send all the data to the DB
            DataLayerResult result = DataLayerSingleton.Instance().InsertRakazEvent(details, PDFB, m_EventID, Comments);
            retval = Convert.ToInt32(result.data);
            return retval;
        }

        private bool SendToRakaz(string path, DSRakazim details, int RakazEventID, bool isReminder)
        {
            bool retval = false;
            //send the pdf to the Rakaz
            try
            {
                string RakazMail = (string)details.GetRakazimToEvent.Rows[0]["Email"];
                MailMessage theMailMessage = new MailMessage("website@hashomer-hatzair.org", RakazMail);
                theMailMessage.Body = "body email message here";
                theMailMessage.Body.PadLeft(60);
                theMailMessage.Attachments.Add(new Attachment(path));
                string subject = txtMailSub.Text;
                string tmp;
                tmp = subject.Replace("event"," "+m_EventName.ToString().Trim()+" ");
                subject= tmp.Replace("link", " " + "http://localhost:2453/HSH-WS/login.aspx?REID=" + RakazEventID + " ");
                theMailMessage.Subject = subject;
                string body = txtMailBody.Text;
                tmp = body.Replace("event", " " + m_EventName.ToString().Trim() + " ");
                body =  tmp.Replace("link", " " + "http://localhost:2453/HSH-WS/login.aspx?REID=" + RakazEventID + " ");
                theMailMessage.BodyEncoding = Encoding.UTF8;
                theMailMessage.Body = body;
                SmtpClient theClient = new SmtpClient("smtp.gmail.com");
                theClient.UseDefaultCredentials = false;
                System.Net.NetworkCredential theCredential = new System.Net.NetworkCredential("website@hashomer-hatzair.org", "sbv cfr");
                theClient.Credentials = theCredential;
                theClient.Send(theMailMessage);
                retval = true;
                theMailMessage.Dispose();
            }
            catch (Exception ex)
            {
                HebMessageBox.Show(ex.Message);
            }
            return retval;
        }

        private void SendReminder()
        {
            DSRakazim pdfds = new DSRakazim();
            DSRakazim.GetRakazimToEventRow row = (DSRakazim.GetRakazimToEventRow)((DataRowView)getRakazimToEventDataGridView.SelectedRows[0].DataBoundItem).Row;
            pdfds.GetRakazimToEvent.ImportRow(row);
            //get the pdf byte array
            byte[] PDFBA;
            DataLayerResult result = DataLayerSingleton.Instance().GetPDF((int)getRakazimToEventDataGridView.SelectedRows[0].Cells["RakazEventID"].Value);
            PDFBA = (byte[])result.data;
            //create temporary pdf path to unBLOB the pdf
            string tempath = "tempPDF.pdf";
            PDFHelper ph = new PDFHelper();
            if (ph.unBlobPDF(PDFBA, tempath))
            {
                bool isSent;
                isSent = SendToRakaz(tempath, pdfds, Convert.ToInt32(pdfds.GetRakazimToEvent.Rows[0]["RakazEventID"]), true);
                if (isSent)
                    HebMessageBox.Show("ההודעה נשלחה ל" + (string)pdfds.GetRakazimToEvent.Rows[0]["FirstName"] + " " + (string)pdfds.GetRakazimToEvent.Rows[0]["LastName"] + @" Email: " + (string)pdfds.GetRakazimToEvent.Rows[0]["Email"]);
            }
            File.Delete(tempath);
        }

        private void SavePDFtofile(string path)
        {
            try
            {
                byte[] PDFBA;
                DataLayerResult result = DataLayerSingleton.Instance().GetPDF((int)getRakazimToEventDataGridView.SelectedRows[0].Cells["RakazEventID"].Value);
                PDFBA = (byte[])result.data;
                PDFHelper ph = new PDFHelper();
                string CityName = getRakazimToEventDataGridView.SelectedRows[0].Cells["jurisdiction"].Value.ToString().Trim();
                string pdfpath = path + CityName + ".pdf";
                string filename = CityName + ".pdf";
                if (File.Exists(pdfpath))
                {
                        throw new Exception("הקובץ " + filename + " כבר קיים בתיקייה שנבחרה, יש למחוק את הקובץ הקיים או לבחור תיקייה אחרת");
                }
                //NEW CONCEPT: Create a new PDF with the Signature and the changes, mark the changes in red and add in the description "with phone authorization"
                //We'll add some text in the comments of the changed rows saying "Changed" and catch that comment in the "CreatePDf" on the pdfhelper.

                //Add here the Code to add the changes made to the PDF since it was approved
                //Use the "CreatePDF" method to create a new Form and stamp a text saying
                //"This is the form containing the changes approved by phone"
                // this will be the form marina will use, but we still have the real form the Rakaz signed.
                //steps:
                //1. Check if Changed
                string tempath= "temp.pdf";
                if (isChanged(getRakazimToEventDataGridView.SelectedRows[0]))
                {
                    ph.unBlobPDF(PDFBA, tempath);
                    //2. get the dataset with Changes
                    DataGridViewRow DGVRow = getRakazimToEventDataGridView.SelectedRows[0];
                    DSRakazim pdfds = new DSRakazim();
                    DSRakazim.GetRakazimToEventRow row = (DSRakazim.GetRakazimToEventRow)ds.GetRakazimToEvent.Rows[DGVRow.Index];
                    pdfds.GetRakazimToEvent.ImportRow(row);
                    foreach (DSRakazim.GetRakazPeopleInEventRow peprow in ds.GetRakazimToEvent.Rows[DGVRow.Index].GetChildRows(ds.Relations[0]))
                    {
                        pdfds.GetRakazPeopleInEvent.ImportRow(peprow);
                    }
                    //3. create a pdf with the changes
                    string ChangesPDFPath = CreatePDF(pdfds);
                    //4. add the stamped text
                    string PdfWithStamp = stampPDF(ChangesPDFPath);
                    //5. join the old pdf with the changed one
                    string[] patharray={PdfWithStamp,tempath};
                    ph.MergeFiles(pdfpath, patharray);
                    foreach (string delpath in patharray)
                        File.Delete(delpath);

                }
                else
                {
                    ph.unBlobPDF(PDFBA, pdfpath);
                }
            }
            catch (Exception ex)
            {
                HebMessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }

        private string stampPDF(string PDFPath)
        {
            string retval = null;
            //Create the pdf and return the path where you put it
            PDFHelper Ph = new PDFHelper();
            try
            {
                retval = Ph.StampChangesOnPDF(PDFPath);
            }
            catch (Exception ex)
            {
                HebMessageBox.Show(ex.Message);
            }
            return retval;
        }

        #endregion

        private int[] CheckedRowsArray()
        {
            int[] retval = new int[CountCheckedRows()];
            int i = 0;
            foreach (DataGridViewRow row in getRakazimToEventDataGridView.Rows)
            {
                if ((bool?)row.Cells["sending"].Value == true)
                {
                    retval[i] = row.Index;
                    i++;
                }

            }
            return retval;
        }

        private int CountCheckedRows()
        {
            int retval = 0;
            foreach (DataGridViewRow row in getRakazimToEventDataGridView.Rows)
            {
                if ((bool?)row.Cells["sending"].Value == true)
                    retval = retval + 1;
            }
            return retval;
        }

        #endregion

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
